//
//  SearchViewController.m
//  bitcoin
//
//  Created by  旺链 on 2018/5/23.
//  Copyright © 2018年 比特币. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchListeTableViewCell.h"
#import "TradeViewController.h"

@interface SearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource>


@property(nonatomic,strong) UISearchBar *searchBar;
@property(nonatomic,strong) UITableView *table;
@property(nonatomic,strong) NSMutableArray *dataArr;
@property(nonatomic,strong) NSMutableArray *temArr;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"搜索币种";
    
    self.temArr = [NSMutableArray array];
//    _temArr = @[@"ETH/USDT",@"ETC/USDT",@"EOS/USDT",@"ZEC/USDT",@"NEO/BTC",@"EOS/BTC",@"ETH/BTC"];
    
    [self.view addSubview:self.searchBar];
    [self.view addSubview:self.table];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    [self getData];
}
- (void)getData
{
    [LSRequestManager getRequestWithURL:HUOBI(@"api/currency/currencyFind") params:nil success:^(NSDictionary *responseData) {
        
        HandleResponse(
                       [self.temArr removeAllObjects];
            [self.temArr addObjectsFromArray:responseData[@"data"]];
        
                       )}
    } failure:^(NSError *error) {
        
    }];
}
- (NSMutableArray *)dataArr
{
    if (!_dataArr) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}
- (UITableView *)table
{
    if (!_table) {
        
        _table = [[UITableView alloc]initWithFrame:CGRectMake(0, self.searchBar.mm_bottom, ScreenWidth, ScreenHeight-self.searchBar.mm_bottom) style:UITableViewStylePlain];
        _table.delegate = self;
        _table.dataSource = self;
        _table.backgroundColor = [UIColor colorWithHexString:@"#1C2035"];
        _table.separatorStyle = UITableViewCellEditingStyleNone;
        
        [_table registerNib:[UINib nibWithNibName:@"SearchListeTableViewCell" bundle:nil] forCellReuseIdentifier:@"SearchListeTableViewCell"];
    }
    return _table;
}
- (UISearchBar *)searchBar
{
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,1,375,44)];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"搜索币种（示例数据输入：EOS）";
        
        UIImage *img = [UIImage imageWithColor:[UIColor colorWithHexString:@"#25293D"] withRect:_searchBar.bounds];
        [_searchBar setBackgroundColor:[UIColor clearColor]];
        [_searchBar setBackgroundImage:img];
        [_searchBar setSearchFieldBackgroundImage:img forState:UIControlStateNormal];
        
        UITextField*searchField = [_searchBar valueForKey:@"_searchField"];
        searchField.textColor = [UIColor whiteColor];
    }
    return _searchBar;
}

- (void)keyboardWillShow:(NSNotification *)aNotification
{
    /* 获取键盘的高度 */
    NSDictionary *userInfo = aNotification.userInfo;
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = aValue.CGRectValue;
    
    self.table.mm_height = ScreenHeight-self.searchBar.mm_bottom-keyboardRect.size.height-60;
}
- (void)keyboardWillHide:(NSNotification *)aNotification
{
    self.table.mm_height = ScreenHeight-self.searchBar.mm_bottom;
}

- (void)requestForFav:(NSString*)relationId
{
    [LSRequestManager postRequestWithURL:MARKET(@"addFav/") params:@{@"relationId":relationId} success:^(NSDictionary *responseData) {
        
        HandleResponse(
            [self getData];
                       )}
        
    } failure:^(NSError *error) {
        
    } showHUD:YES];
}
#pragma mark searchBar
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    NSLog(@"%@",searchText);
    
    [self.dataArr removeAllObjects];
    for (NSDictionary *dic in self.temArr) {
        
        if ([dic[@"value"] containsString:searchText.uppercaseString]) {
            
            [self.dataArr addObject:dic];
            
        }
    }
    [self.table reloadData];
}

#pragma mark tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SearchListeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchListeTableViewCell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    NSDictionary *dic = self.dataArr[indexPath.row];
    cell.nameLb.text = dic[@"value"];
    cell.favBtn.selected = [dic[@"fav"]integerValue]==1?YES:NO;
    cell.favClick = ^{
        
        [self requestForFav:dic[@"id"]];
    };
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic= self.dataArr[indexPath.row];
    
    self.tabBarController.selectedIndex = 2;
    UINavigationController *nav = (UINavigationController*)(self.tabBarController.childViewControllers[2]);
    TradeViewController *vc = (TradeViewController*)nav.visibleViewController;
    if (!vc.relation.length) {
        [vc viewDidLoad];
    }
    

    vc.relationId = dic[@"id"];
    vc.relation = dic[@"value"];
    vc.isBuy = YES;
//    [vc getData];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
